package com.example.xunua_mymusic;

import androidx.appcompat.app.AppCompatActivity;

import androidx.drawerlayout.widget.DrawerLayout;

import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.xunua_mymusic.entitys.Music;
import com.example.xunua_mymusic.utils.FragmentUtils;
import com.example.xunua_mymusic.utils.GetMusicList;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends AppCompatActivity implements KeyEvent.Callback ,SeekBar.OnSeekBarChangeListener,MediaPlayer.OnCompletionListener, View.OnTouchListener {
    ListView listView;
    DrawerLayout chouti;
    SeekBar seekBar;
    MediaPlayer mediaPlayer;
    int index=0;
    boolean first=true;
    ArrayList<Music> musics;
    ImageView img_bofang;
    TextView tv_start,tv_end,tv_musciname;
    Boolean isChanging=false;
    LinearLayout line;
    ImageView img_menu;
    //不是https协议的不会读
    String[] url={"https://gss0.bdstatic.com/-4o3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike180%2C5%2C5%2C180%2C60/sign=c2ed57fdc11b9d169eca923392b7dfea/838ba61ea8d3fd1ff51f67183f4e251f95ca5ffa.jpg"
    ,"https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3870624064,817958255&fm=26&gp=0.jpg",
    "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=446847103,202567191&fm=26&gp=0.jpg",
            "https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=362237830,1699360118&fm=26&gp=0.jpg",
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1571376122961&di=ccd1dd7fc24254c9d1f46ab1115ca51c&imgtype=0&src=http%3A%2F%2Fphotocdn.sohu.com%2F20150325%2FImg410299068.jpg",
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1571376122959&di=b4014bbf57b1da04e17aa9323fdda69f&imgtype=0&src=http%3A%2F%2Fimg3.duitang.com%2Fuploads%2Fitem%2F201605%2F07%2F20160507212554_unYEC.thumb.700_0.jpeg",
            "https://up.enterdesk.com/edpic/e0/0f/09/e00f0965bb021fc18d26a3ff9deb6960.jpg"
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        fragment();
        musics=new ArrayList<>();
        musics.clear();
        musics.addAll(getMusic());
    }

    public String getUserName(){
        return getIntent().getStringExtra("username");
    }

    /**
     *
     * @return   本地音乐歌单
     */
    public ArrayList<Music> getMusic(){
        GetMusicList getMusicList;
        ContentResolver contentResolver;
        ArrayList<Music> musicList;
        musicList=new ArrayList<>();
        getMusicList=new GetMusicList();
        contentResolver= getContentResolver();
        musicList.clear();
        musicList.addAll(getMusicList.getMusic(contentResolver));
        for (int i = 0; i < musicList.size(); i++) {
            Log.e("TAG", "getMusic: "+musicList.get(i).getTitle() );
        }
        return musicList;
    }

    /**
     *  MedioPlayer的使用
     * @return
     */
        public void playMusic(int position){
            first=false;
            //1、设置进度条
            seekBar.setProgress(0);
            seekBar.setMax((int) musics.get(position).getDuration());
            //2、播放音乐
            // 2.1、重置MediaPlayer
            mediaPlayer.reset();//重置MediaPlayer
            //2.2播放音乐
            //获取音乐路径
            try {
                String url=musics.get(position).getUrl();
                mediaPlayer.setDataSource(url);//设置读取路径
                mediaPlayer.prepare();//准备
                mediaPlayer.start();//播放
            } catch (IOException e) {
                e.printStackTrace();
            }

            SimpleDateFormat sdf=new SimpleDateFormat("mm:ss");
            String time=sdf.format(musics.get(position).getDuration());
            tv_end.setText(time);
            //设置播放器歌曲名 和歌手
            tv_musciname.setText(musics.get(position).getTitle());

            //更新进度条
            Timer mTimer = new Timer();
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    if(isChanging==true) {
                        return;
                    }
                    seekBar.setProgress(mediaPlayer.getCurrentPosition());
                }
            };
            mTimer.schedule(timerTask, 0, 600);
            img_bofang.setImageResource(R.mipmap.img_appwidget91_voice_pause_normal);

            //读取网络图片
            Random random=new Random();
            int i = random.nextInt(url.length);
            Picasso.with(this).load(url[i]).into(img_menu);
        }

    /**
     *  判断mp是否为null 以及是否处于stop状态
     */
        public void isPlayMusic(){
            if (mediaPlayer != null) {
                if (!mediaPlayer.isPlaying()) {
                    playMusic(index);
                }
            }else {
                mediaPlayer=new MediaPlayer();
                playMusic(index);
            }
        }

        //上一首
        public void lastMusic(){
            if (mediaPlayer != null) {
                if (index==0){
                    //判断是不是第一首
                    index=musics.size()-1;
                }else {
                    --index;
                }
                isPlayMusic();
            }
        }
        public void setIndex(int index){
            this.index=index;
        }
        public void nextMusic(){
            if (mediaPlayer != null) {
                if (index == musics.size() - 1) {
                    index=0;
                }else {
                    ++index;
                }
                isPlayMusic();
            }
        }

        public void pause(){
            mediaPlayer.pause();
        }
    /**
     *
     */
    private void fragment(){
        FragmentUtils fragmentUtils=new FragmentUtils();
        fragmentUtils.show(getSupportFragmentManager(),0);
    }
    private void init(){
        img_menu=findViewById(R.id.main_music_img);

//        //由于line点击事件和touch事件冲突 将点击事件放于图片中
//        img_menu.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                AFactory.A=MainActivity.this;
//                Intent intent=new Intent(MainActivity.this,playActivity.class);
//                startActivity(intent);
//            }
//        });
        line=findViewById(R.id.main_line_music);
        line.setOnTouchListener(this);
        tv_musciname=findViewById(R.id.main_music_name);
        tv_start=findViewById(R.id.main_tv_time_start);
        tv_end=findViewById(R.id.main_tv_time_end);
        chouti=findViewById(R.id.chouti);
        listView=findViewById(R.id.activity_main_left_ListView);
        listView.setAdapter(new MyAdapter());
        seekBar=findViewById(R.id.main_seekbar);
        seekBar.setOnSeekBarChangeListener(this);
        mediaPlayer=new MediaPlayer();
        mediaPlayer.setOnCompletionListener(this);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                chouti.closeDrawer(Gravity.LEFT);
                switch (position){
                    case 3:

                        break;
                    case 8:

                        break;
                    case 9:
                        System.exit(0);
                        break;
                }
            }
        });
        img_bofang=findViewById(R.id.activity_main_img_bofang);
        img_bofang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mediaPlayer.isPlaying()) {
                    img_bofang.setImageResource(R.mipmap.img_appwidget91_voice_pause_normal);
                    if (first){
                        isPlayMusic();
                    }else {
                        if (mediaPlayer == null) {
                            mediaPlayer=new MediaPlayer();
                            isPlayMusic();
                        }else {
                            if (!mediaPlayer.isPlaying()) {
                                mediaPlayer.start();
                            } else {
                                isPlayMusic();
                            }
                        }
                    }
                }else if (mediaPlayer.isPlaying()){
                    img_bofang.setImageResource(R.mipmap.img_appwidget91_voice_play_normal);
                    mediaPlayer.pause();
                }
            }
        });
    }

    /**
     *              当一首音乐播放完毕后，会自动调用此方法
     * @param mp
     */
    @Override
    public void onCompletion(MediaPlayer mp) {
        mp.reset();
        nextMusic();
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        SimpleDateFormat sdf=new SimpleDateFormat("mm:ss");
        String time=sdf.format(seekBar.getProgress());
        tv_start.setText(time);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        isChanging=true;
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (mediaPlayer != null) {
            mediaPlayer.seekTo(seekBar.getProgress());
        }
        isChanging=false;
    }

    //滑动切歌事件
    //触摸事件的起始值和末值必须设置为成员变量
    //手指按下的x y;
    float xDown=0;
    float yDown=0;
    //手指松开的x y坐标
    float xUp=0;
    float yUp=0;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        //判断当前的触摸事件是否是按下事件
        if (MotionEvent.ACTION_DOWN == event.getAction()) {
            //当手指按下
            xDown=event.getX();
            yDown=event.getY();
            isChanging=true;
        }
        if (MotionEvent.ACTION_UP == event.getAction()) {
            //当手指松开
            xUp=event.getX();
            yUp=event.getY();

            //放在这里面以保证此滑动事件一次滑动只执行一次滑动事件
            if (yDown - yUp < 40 && yDown - yUp > -40) {
                if (xDown - xUp > 50) {
                    //左滑
                    mediaPlayer.pause();
                    lastMusic();
//                    isChanging=true;
//                    handler.sendEmptyMessageDelayed(1,1000);
                }else if (xDown-xUp<-50){
                    //右滑
                    mediaPlayer.pause();
                    nextMusic();
//                    isChanging=true;
//                    handler.sendEmptyMessageDelayed(1,1000);
                }
            }
            isChanging=false;
        }
        return true;
    }

//    //来电处理
//    protected void onDestroy() {
//        if(player != null){
//            if(player.isPlaying()){
//                player.stop();
//            }
//            player.release();
//        }
//        super.onDestroy();
//    }
//
//    protected void onPause() {
//        if(player != null){
//            if(player.isPlaying()){
//                player.pause();
//            }
//        }
//        super.onPause();
//    }
//
//    protected void onResume() {
//        if(player != null){
//            if(!player.isPlaying()){
//                player.start();
//            }
//        }
//        super.onResume();
//    }
    private class MyAdapter extends BaseAdapter{
        String[] titles={"仅WIFI联网","透明模式","壁纸&皮肤","睡眠模式","滴滴求歌","音效","音乐包","设置","扫描音乐","退出"};
        @Override
        public int getCount() {
            return titles.length;
        }

        @Override
        public Object getItem(int position) {
            return titles[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder=null;
            if (convertView == null) {
                holder=new ViewHolder();
                convertView= LayoutInflater.from(getApplicationContext()).inflate(R.layout.lv_activity,null);
                holder.tv=convertView.findViewById(R.id.lv_activity_title);
                convertView.setTag(holder);
            }else {
                holder= (ViewHolder) convertView.getTag();
            }

            holder.tv.setText(titles[position]+"");
            return convertView;
        }
        private class ViewHolder{
            TextView tv;
        }
    }

    long time=0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK) {
            if (System.currentTimeMillis() - time > 2000) {
                Toast.makeText(getApplicationContext(), "再次点击退出程序!", Toast.LENGTH_SHORT).show();
                time=System.currentTimeMillis();
            }else {
                //退出后清空歌单存储文件（便于测试）
                SharedPreferences sharedPreferences=getSharedPreferences("MusicList", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.clear();
                edit.commit();
                moveTaskToBack(true);
                System.exit(0);
                System.gc();
            }
        }
        return false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
    }

}
